/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import { watchWorker } from '@ohos/hvigor';
import { ProjectConfig } from '@ohos/hvigor-arkts-compose';
import * as fse from 'fs-extra';
import { Level } from 'log4js';
import path from 'path';

import { OhosLogger } from '../utils/log/ohos-logger.js';

import { ArkCompile } from './ark-compile.js';

export class HotReloadArkCompile extends ArkCompile {
  logger: OhosLogger = OhosLogger.getLogger(HotReloadArkCompile.name);

  protected async doTaskAction(): Promise<void> {
    const buildConfigPath: string = this.pathInfo.getBuildConfigPath();
    let compileConfig;
    let patchConfig;
    if (fse.existsSync(buildConfigPath)) {
      const buildConfig = fse.readJsonSync(buildConfigPath);
      compileConfig = buildConfig.compileConfig;
      patchConfig = buildConfig.patchConfig;
    } else {
      this.logger.debug(`Build config file not found: ${buildConfigPath}`);
    }
    const config: ProjectConfig = {
      ...(await this.initDefaultArkCompileConfig()),
      ...(compileConfig ?? {}),
      cachePath: this.getTaskTempDir(this.targetData),
    };
    if (config.obfuscationOptions) {
      delete config.obfuscationOptions;
    }
    config.aceModuleJsonPath = this.aceModuleJsonPath;
    config.watchMode = 'true';
    config.projectPath = config.aceModuleRoot;
    fse.ensureDirSync(config.cachePath!);
    fse.ensureDirSync(config.aceModuleBuild!);
    this._log.debug(`build config: ${config}`);
    if (patchConfig && config.aceBuildJson && fse.existsSync(config.aceBuildJson)) {
      const loaderConfig = fse.readJsonSync(config.aceBuildJson);
      loaderConfig.patchConfig = patchConfig;
      fse.outputJSONSync(config.aceBuildJson, loaderConfig);
    }
    const workerId = watchWorker.createWorker(
      this,
      path.resolve(__dirname, './worker/hot-reload-build.js'),
      true,
      (compileEvents: object[]) => this.handleCompileEvents(compileEvents, this.getSubDurationEvent(workerId), true),
      {
        workerData: {
          projectConfig: config,
          logLevel: (this.logger.getLevel() as Level).levelStr,
        },
      },
    );
  }

  initTaskDepends(): void {
    this.dependsOnHook('buildHotReloadResource');
  }
}
